package redis

import (
	"fmt"
	"gin/app/http/global"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
	"sync"
	"time"
)

var mu sync.Mutex

func InitRedis(c *gin.Context) (err error) {
	mu.Lock()
	defer mu.Unlock()
	Rdb := redis.NewClient(&redis.Options{
		Addr:       viper.GetString("redis.host") + ":" + viper.GetString("redis.port"),
		Password:   viper.GetString("redis.password"),
		DB:         viper.GetInt("redis.db"),
		PoolSize:   20,
		MaxConnAge: 10 * time.Second,
	})
	_, err = Rdb.Ping(c).Result()
	if err != nil {
		return err
	}
	global.Rdb = Rdb
	fmt.Println("redis连接成功")
	return nil
}
